#include "proc/loadavg.h"

static bool proc_loadavg_of_buffer(char *buf, ProcLoadAvg *loadavg) {
    if(isNull(buf)) return false;

    LineTrim_buf(buf, buf);
    
    GSList *list = split(buf, ' ');
    if (g_slist_length(list) > 4) {
        loadavg->one = atof(g_slist_nth(list, 0)->data);
        loadavg->two = atof(g_slist_nth(list, 1)->data);
        loadavg->three = atof(g_slist_nth(list, 2)->data);
        strcpy(loadavg->pro, g_slist_nth(list, 3)->data);
        loadavg->recentlyPid = atof(g_slist_nth(list, 4)->data);
    }
    GS_FREE_ALL_CLEAN(list);

    return true;
}

bool initLoadAvg(ProcLoadAvg *loadavg) {
    if(!FileExists(LINUX_OS_PROC_LOADAVG)) return false;

    char buffer[100] = {0};

    if (FileReadToBuffer(LINUX_OS_PROC_LOADAVG, buffer, sizeof(buffer))) {
        return proc_loadavg_of_buffer(buffer, loadavg);
    }
    return false;
}